package com.geekgo.ladder.core.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.geekgo.ladder.core.Constants;
import com.geekgo.ladder.core.exception.BaseException;
import com.geekgo.ladder.core.exception.IllegalParameterException;
import com.geekgo.ladder.core.support.HttpCode;
import com.geekgo.ladder.core.util.WebUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author geekgo
 * @version 2016/12/22 14:18
 */
public abstract class BaseController {
    protected final Logger LOG = LogManager.getLogger(getClass());

    /**
     * 获取当前登录用户ID
     * @return
     */
    protected Long getCurrentUserId(){
        return WebUtil.getCurrentUserId();
    }

    /**设置成功响应代码*/
    protected ResponseEntity<ModelMap> setSuccessModelMap(ModelMap modelMap){
        return setSuccessModelMap(modelMap,null);
    }
    /**设置成功响应代码*/
    protected ResponseEntity<ModelMap> setSuccessModelMap(ModelMap modelMap,Object data){
        return setModelMap(modelMap,HttpCode.OK,data);
    }
    /**设置响应代码*/
    protected ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, HttpCode httpCode){
        return setModelMap(modelMap,httpCode,null);
    }
    /**设置响应代码*/
    protected ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, HttpCode httpCode,Object data){
        modelMap.remove("void");
        if(null!=data){
            modelMap.put("data",data);
        }
        modelMap.put("httpCode",httpCode.value());
        modelMap.put("msg",httpCode.msg());
        modelMap.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(modelMap);
    }
    @ExceptionHandler(Exception.class)
    public void exceptionHandler(HttpServletRequest request, HttpServletResponse response,Exception ex)throws Exception{
        LOG.error(Constants.EXCEPTION_HEADER);
        ModelMap modelMap = new ModelMap();
        if(ex instanceof BaseException){
            ((BaseException)ex).handler(modelMap);
        }else if(ex instanceof IllegalArgumentException){
            new IllegalParameterException(ex.getMessage()).handler(modelMap);
        }else if(ex instanceof UnauthorizedException){
            setModelMap(modelMap,HttpCode.FORBIDDEN);
        }else{
            setModelMap(modelMap,HttpCode.INTERNAL_SERVER_ERROR);
        }
        request.setAttribute("msg", modelMap.get("msg"));
        response.setContentType("application/json;charset=UTF-8");
        byte[] bytes = JSON.toJSONBytes(modelMap, SerializerFeature.DisableCircularReferenceDetect);
        response.getOutputStream().write(bytes);
    }
}
